package cn.wolfcode.web.controller;

import cn.wolfcode.query.CustomerReportQuery;
import cn.wolfcode.service.ICustomerReportService;
import cn.wolfcode.util.MessageUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/customerReport")
public class CustomerReportController {
    @Autowired
    private ICustomerReportService customerReportService;

    //跳转到报表页面
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") CustomerReportQuery qo){
        model.addAttribute("pageInfo",customerReportService.selectCustomerReport(qo));
        return "customerReport/list";
    }


    /**
     * 访问柱状图页面
     * @param model
     * @param qo
     * @return
     */
    @RequestMapping("/bar")
    public String listByBar(Model model, @ModelAttribute("qo") CustomerReportQuery qo){
        //获取所有数据
        List<HashMap> data = customerReportService.listAll(qo);
        //提供两个集合存储data集合里面map的数据
        ArrayList<Object> xList = new ArrayList<>();
        ArrayList<Object> yList = new ArrayList<>();

        //遍历data
        for (Map map : data) {
            xList.add(map.get("groupType"));
            yList.add(map.get("number"));
        }

        //共享到页面     (freemarker要转换为string字符串的格式)
        model.addAttribute("xList", JSON.toJSONString(xList));
        model.addAttribute("yList",JSON.toJSONString(yList));
        //分组中文名
        model.addAttribute("groupTypeName", MessageUtil.changMsg(qo));
        //跳转页面
        return "customerReport/bar";
    }


    /**
     * 访问饼状图页面
     * @param model
     * @param qo
     * @return
     */
    @RequestMapping("/pie")
    public String listByPie(Model model, @ModelAttribute("qo") CustomerReportQuery qo){
        //获取所有数据(不分页)
        List<HashMap> data = customerReportService.listAll(qo);
        //提供两个集合存储  分组类型的数据
        ArrayList<Object> legendList = new ArrayList<>();
        ArrayList<Object> seriesList = new ArrayList<>();

        //遍历map
        for (HashMap map : data) {
            legendList.add(map.get("groupType"));
            //new一个hashmap
            HashMap<String, Object> obj = new HashMap<>();
            obj.put("name",map.get("groupType"));
            obj.put("value",map.get("number"));
            seriesList.add(obj);
        }

        //共享到页面     (freemarker要转换为string字符串的格式)
        model.addAttribute("legendList", JSON.toJSONString(legendList));
        model.addAttribute("seriesList", JSON.toJSONString(seriesList));
        //分组中文名
        model.addAttribute("groupTypeName", MessageUtil.changMsg(qo));

        //跳转页面
        return "customerReport/pie";
    }
}
